/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */
import fs from 'fs';
import path from 'path';

import { DEFAULT_HVIGOR_CONFIG_JSON_FILE_NAME } from '../../common/const/const.js';
import { HVIGOR_PROJECT_WRAPPER_HOME } from '../../common/const/path-const.js';
import { parseJsonFile } from '../../common/util/parse-json/parse-json-util.js';

export function checkHvigorConfigBeforeProgram(cliArgv: any, logger: any) {
  try {
    if (!fs.existsSync(path.resolve(HVIGOR_PROJECT_WRAPPER_HOME, DEFAULT_HVIGOR_CONFIG_JSON_FILE_NAME))) {
      return { result: true };
    }
    parseJsonFile(path.resolve(HVIGOR_PROJECT_WRAPPER_HOME, DEFAULT_HVIGOR_CONFIG_JSON_FILE_NAME));
    return { result: true };
  } catch (e: any) {
    if (e instanceof Error) {
      let errorMsg = `${e.message}`;
      if (cliArgv.stacktrace && e.stack) {
        errorMsg += `${e.stack}\n`;
      }
      logger.printError('SYNTAX_ERROR_IN_HVIGOR_CONFIG_JSON5', [errorMsg]);
      return { result: false, message: errorMsg };
    }
    return { result: false, stack: e?.stack, message: e.message };
  }
}
